package org.csu.mybigpro.controller;

import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.domain.QuizGameSession;
import org.csu.mybigpro.service.IQuizGameService;
import org.csu.mybigpro.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

@RestController
@RequestMapping("/api/quiz-game")
public class QuizGameController {

    @Autowired
    private IQuizGameService quizGameService;

    @PostMapping("/start")
    public CommonResponse<?> startGame(@RequestBody Map<String, String> payload) {
        String topic = payload.get("topic");
        String difficulty = payload.get("difficulty");
        Integer userId = UserContext.getCurrentUserId(); // 从JWT拦截器获取用户ID

        if (userId == null) {
            return CommonResponse.createForError("用户未登录，无法开始游戏。");
        }
        if (topic == null || topic.isBlank()) {
            return CommonResponse.createForError("必须提供游戏主题。");
        }

        try {
            QuizGameSession session = quizGameService.startGame(topic, difficulty, userId);
            // 为了安全和简洁，只返回必要的信息给前端
            Map<String, Object> gameData = Map.of(
                    "sessionId", session.getId(),
                    "questions", session.getQuestions()
            );
            return CommonResponse.createForSuccess("游戏创建成功", gameData);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
        }
    }

    @PostMapping("/submit")
    public CommonResponse<?> submitAnswer(@RequestBody Map<String, Object> payload) {
        // --- 修正和健壮性增强从这里开始 ---
        Long sessionId;
        Object sessionIdObj = payload.get("sessionId");
        if (sessionIdObj == null) {
            return CommonResponse.createForError("缺少会话ID（sessionId）参数。");
        }
        if (sessionIdObj instanceof Number) {
            sessionId = ((Number) sessionIdObj).longValue();
        } else if (sessionIdObj instanceof String) {
            try {
                sessionId = Long.parseLong((String) sessionIdObj);
            } catch (NumberFormatException e) {
                return CommonResponse.createForError("会话ID（sessionId）格式不正确，必须为数字。");
            }
        } else {
            return CommonResponse.createForError("会话ID（sessionId）类型不正确。");
        }

        int questionIndex;
        Object questionIndexObj = payload.get("questionIndex");
        if (questionIndexObj == null) {
            return CommonResponse.createForError("缺少问题索引（questionIndex）参数。");
        }
        if (questionIndexObj instanceof Number) {
            questionIndex = ((Number) questionIndexObj).intValue();
        } else if (questionIndexObj instanceof String) {
            try {
                questionIndex = Integer.parseInt((String) questionIndexObj);
            } catch (NumberFormatException e) {
                return CommonResponse.createForError("问题索引（questionIndex）格式不正确，必须为数字。");
            }
        } else {
            return CommonResponse.createForError("问题索引（questionIndex）类型不正确。");
        }

        String answer = (String) payload.get("answer");
        if (answer == null || answer.isBlank()) {
            return CommonResponse.createForError("必须提供答案。");
        }
        // --- 修正和健壮性增强到这里结束 ---

        try {
            Map<String, Object> result = quizGameService.submitAnswer(sessionId, questionIndex, answer);
            return CommonResponse.createForSuccess("答案提交成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.createForError("提交失败：" + e.getMessage());
        }
    }
}